Page({
    data: {
      phone: '',
      code: '',
      isCountingDown: false,
      countdown: 60
    },
  
    onClickLeft() {
      console.log("123");
      const pages = getCurrentPages();
      if (pages.length > 1) {
        wx.navigateBack({
          delta: 1,
          success: function() {
            console.log('成功返回上一页');
          },
          fail: function(err) {
            console.error('返回上一页失败:', err);
          }
        });
      } else {
        console.log('当前页面栈中只有一个页面，无法返回上一页');
      }
    },
  
    // 发送验证码
    sendCode() {
      if (!this.data.phone || this.data.phone.length !== 11) {
        wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }
  
      // 显示发送提示
      wx.showToast({
        title: '验证码已发送至' + this.data.phone,
        icon: 'none'
      });
  
      // 开始倒计时
      this.setData({
        isCountingDown: true
      });
  
      let interval = setInterval(() => {
        if (this.data.countdown <= 1) {
          clearInterval(interval);
          this.setData({
            isCountingDown: false,
            countdown: 60
          });
        } else {
          this.setData({
            countdown: this.data.countdown - 1
          });
        }
      }, 1000);
    },
  
    onPhoneInput(e) {
      this.setData({
        phone: e.detail.value
      });
    },
  
    // 验证码输入
    onCodeInput(e) {
      this.setData({
        code: e.detail.value
      });
    },
  
    bindPhone() {
      const { phone, code } = this.data;
      
      if (!phone) {
        wx.showToast({
          title: '请输入手机号',
          icon: 'none'
        });
        return;
      }
      
      if (!code) {
        wx.showToast({
          title: '请输入验证码',
          icon: 'none'
        });
        return;
      }
  
      const app = getApp();
      const userId = app.globalData.userId;
      if (!userId) {
        wx.showToast({
          title: '用户未登录',
          icon: 'none'
        });
        return;
      }
  
      wx.request({
        url: 'http://localhost:8080/pubUser/bindPhone',
        method: 'PUT',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': 'Bearer token'
        },
        data: {
          id: userId,
          phone,
          code  // 添加验证码参数
        },
        success: (res) => {
          if (res.data.code === 1) {
            wx.showToast({
              title: '绑定手机号成功',
              icon: 'success'
            });
            wx.navigateBack();
          } else {
            wx.showToast({
              title: res.data.msg || '绑定手机号失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        }
      });
    }
  });
  